package org.shopping.dao.commodity.impl;

import org.shopping.dao.commodity.CommodityDao;
import org.shopping.domain.Commodity;
import org.shopping.utils.JDBCUtils2;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.List;

public class CommodityDaoImpl implements CommodityDao {

    // 创建模板对象
    private JdbcTemplate jt = new JdbcTemplate(JDBCUtils2.getDataSource());

    @Override
    public List<Commodity> selectAll() {
        // 编写sql
        String sql = "select * from tab_commodity";
        // 执行sql
        List<Commodity> list = jt.query(sql, new BeanPropertyRowMapper<Commodity>(Commodity.class));
        return list;
    }

    @Override
    public List<Commodity> findByPage(Integer currentPage, Integer pageSize) {
        // 编写sql
        String sql = "select * from tab_commodity limit ?,?";
        // 执行sql
        List<Commodity> list = jt.query(sql, new BeanPropertyRowMapper<Commodity>(Commodity.class),
                (currentPage-1)*pageSize,
                pageSize
        );
        return list;
    }

    @Override
    public Number findTotalCount() {
        Number totalCount = jt.queryForObject("select count(cid) from tab_commodity", Number.class);
        return totalCount;
    }

    @Override
    public int deleteCommodity(String cidForm) {
        // 编写sql
        String sql = "delete from tab_commodity where cid=?";
        // 执行sql
        int row = jt.update(sql, cidForm);
        return row;
    }

    @Override
    public Commodity findCommodity(String cidForm) {
        // 编写sql
        String sql = "select * from tab_commodity where cid=?";
        // 执行sql
        Commodity commodity = jt.queryForObject(sql, new BeanPropertyRowMapper<Commodity>(Commodity.class), cidForm);
        return commodity;
    }

    @Override
    public int updateCommodity(Commodity commodity, String updateCid) {
        // 编写sql
        String sql = "update tab_commodity set cid=?, cname=?, cprice=?, cshop=?, cimg=?, csales=? where cid=?";
        // 执行sql
        int row = jt.update(sql, commodity.getCid(), commodity.getCname(), commodity.getCprice(), commodity.getCshop(), commodity.getCimg(), commodity.getCsales(), updateCid);
        return row;
    }

    @Override
    public int addCommodity(Commodity commodity) {
        // 编写sql
        String sql = "insert into tab_commodity values(?,?,?,?,?,?)";
        // 执行sql
        int row = jt.update(sql, commodity.getCid(), commodity.getCname(), commodity.getCprice(), commodity.getCshop(), commodity.getCimg(), commodity.getCsales());
        return row;
    }
}










